//
//  CategoryViewController.m
//  ShopXinyi
//
//  Created by qianfeng on 15/9/14.
//  Copyright (c) 2015年 qianfeng. All rights reserved.
//

#import "CategoryViewController.h"
#import "HttpRequestManager.h"
#import "UIImageView+AFNetworking.h"
#import "CateBrandsModel.h"
#import "CateClassModel.h"
#import "cateGoodsModel.h"
#import "CateGoodClassModel.h"
#import "CateBigCell.h"
#import "CateBrandCell.h"

@interface CategoryViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    NSMutableArray *_classArray;
    NSMutableArray *_showClassArray;
    NSArray *_className;
    int _currentClass;  //类别排列
}

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *mySegmented;


@end

@implementation CategoryViewController
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        _classArray = [NSMutableArray new];
        _showClassArray = [NSMutableArray new];
        _className = @[@"零食特产",@"茶冲乳品",@"美容化妆",@"母婴用品",@"家居清洁",@"办公用品",@"家用电器",@"滋补药品",@"服饰鞋帽",@"箱包配饰",@"代买代送",@"礼品"];
        _currentClass = 0;
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [self requestDataFromNet];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.view addGestureRecognizer:tap];
    
    [_myCollectionView registerNib:[UINib nibWithNibName:@"CateBigCell" bundle:nil] forCellWithReuseIdentifier:@"CateBigCell"];
    [_myCollectionView registerNib:[UINib nibWithNibName:@"CateBrandCell" bundle:nil] forCellWithReuseIdentifier:@"CateBrandCell"];
    [_mySegmented addTarget:self action:@selector(classOrBrands:) forControlEvents:UIControlEventValueChanged];

}

-(void)classOrBrands:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        [_myCollectionView reloadData];
    }else{
        [_myCollectionView reloadData];
    }
}

-(void)tap
{
    [self.view endEditing:YES];
}

-(void)requestDataFromNet
{
    [[HttpRequestManager shareInstance]getClassPageInfoSuccess:^(id responseObj) {
        NSArray *classlistArray = responseObj;
        for (NSDictionary *classDic in classlistArray) {
            NSArray *array = classDic[@"brands"];
            NSMutableArray *brandsArray = [NSMutableArray new];
            for (NSDictionary *dic in array) {
                CateBrandsModel *model = [CateBrandsModel new];
                model.brandID = dic[@"brand_id"];
                model.brandName = dic[@"brand_name"];
                model.brandPic = dic[@"brand_pic"];
                [brandsArray addObject:model];
            }
            CateClassModel *model = [CateClassModel new];
            model.brandsArray = brandsArray;
            model.classid = classDic[@"gc_id"];
            model.className = classDic[@"gc_name"];
            model.typeID = classDic[@"type_id"];
            model.typeName = classDic[@"type_name"];
            
            [self requestClassDataFromNetWithClassID:model.classid];

            [_classArray addObject:model];
        }
        
        [_myTableView reloadData];

    } failure:^(NSError *error) {
        
    }];
}


-(void)requestClassDataFromNetWithClassID:(NSString*)goodClassID
{
    [[HttpRequestManager shareInstance]getClassPageInfoWithID:goodClassID Success:^(id responseObj) {
        NSArray *array = responseObj;
        NSMutableArray *showArray = [NSMutableArray new];
        for (NSDictionary *classDic in array) {
            NSArray *classArray = classDic[@"class3"];
            NSMutableArray *goodsArray = [NSMutableArray new];
            if (![classArray isKindOfClass:[NSNull class]]){
                for (NSDictionary *dic in classArray) {
                    cateGoodsModel *model = [cateGoodsModel new];
                    model.goodid = dic[@"gc_id"];
                    model.goodName = dic[@"gc_name"];
                    model.goodParentID = dic[@"gc_parent_id"];
                    model.goodUtime = dic[@"gc_utime"];
                    model.typeID = dic[@"type_id"];
                    
                    [[HttpRequestManager shareInstance] getClassPictureWithGoodsID:model.goodid success:^(id responseObj) {
                        model.imageURL = responseObj;
                    } failure:^(NSError *error) {
                        NSLog(@"获取 class 图片失败,error==%@",error);
                    }];
                    
                    [goodsArray addObject:model];
                }
            }
            CateGoodClassModel *model = [CateGoodClassModel new];
            model.goodsArray = goodsArray;
            model.gcID = classDic[@"gc_id"];
            model.gcName = classDic[@"gc_name"];
            model.gcParentID =classDic[@"gc_parent_id"];
            model.gcSort =classDic[@"gc_sort"];
            model.typeID =classDic[@"type_id"];
            [showArray addObject:model];
        }
        [_showClassArray addObject:showArray];
        [_myCollectionView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"请求列别列表失败,error==%@",error);
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -UITableViewDelegate&UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 12;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reusedID = @"reusedID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusedID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusedID];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = _className[indexPath.row];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.font = [UIFont systemFontOfSize:12];
    cell.selectedBackgroundView = [[UIView alloc]initWithFrame:cell.bounds];
    cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _currentClass = (int)indexPath.row;
    [_myCollectionView reloadData];
}



#pragma mark -UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_mySegmented.selectedSegmentIndex == 0) {
        if (_showClassArray.count > 0) {
            NSArray *currentArray = _showClassArray[_currentClass];
            return currentArray.count;
        }
    }else{
        CateClassModel *model = _classArray[_currentClass];
        NSArray *brandsArray = model.brandsArray;
        if (brandsArray.count > 0) {
            return brandsArray.count;
        }
    }
    return 0;
}

//cell 复用
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_mySegmented.selectedSegmentIndex == 0) {
        CateBigCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CateBigCell" forIndexPath:indexPath];
        NSArray *currentArray = _showClassArray[_currentClass];
        CateGoodClassModel *model = currentArray[indexPath.row];
        cell.goodsArray = model.goodsArray;
        cell.gcName = model.gcName;
        [cell.littleCollectionView reloadData];
        return cell;
    }else{
        
        CateBrandCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CateBrandCell" forIndexPath:indexPath];
        CateClassModel *model = _classArray[_currentClass];
        NSArray *brandsArray = model.brandsArray;
        CateBrandsModel *brandModel = brandsArray[indexPath.row];
        cell.brandLabel.text = brandModel.brandName;
        return cell;
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_mySegmented.selectedSegmentIndex == 0) {
        if (_showClassArray.count > 0) {
            NSArray *currentArray = _showClassArray[_currentClass];
            CateGoodClassModel *model = currentArray[indexPath.row];
            NSInteger num = model.goodsArray.count;
            if (num % 3 > 0) {
                num = num / 3 + 1;
            }else{
                num = num / 3;
            }
            if (num == 0) {
                return CGSizeMake(_myCollectionView.frame.size.width, 0.00001);
            }
            return CGSizeMake(_myCollectionView.frame.size.width, _myCollectionView.frame.size.width*num*0.4+30);
            
        }else{
            return CGSizeMake(_myCollectionView.frame.size.width, 0.00001);
        }
    }else
        return CGSizeMake(60, 30);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(_myCollectionView.frame.size.width, 40);
}


@end
